package com.thuanhoang.boo;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.BooPreference;
import util.Constant;
import util.Utility;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.boo.service.AccountService;
import com.boo.service.SendDataService;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.thuanhoang.boo.adapter.FeedListAdapter;
import com.thuanhoang.boo.model.Feed;
import com.thuanhoang.boo.model.Merchant;
import com.thuanhoang.boo.model.ObjUser;

public class HomeActivity extends Activity{
	public static ArrayList<Merchant> merch_list;
	ListView list_feed;
	ArrayList<Feed> feed_list;
	FeedListAdapter feedAdapter;
	View btnAccount;
	View btnChannel;
	private static ProgressDialog waitDialog;
	public static ObjUser userInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		merch_list = new ArrayList<Merchant>();
		feed_list = new ArrayList<Feed>();
		list_feed = (ListView) findViewById(R.id.list_feed);
		
		
		feedAdapter = new FeedListAdapter(this, feed_list);
		list_feed.setAdapter(feedAdapter);
		list_feed.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				String merchId = feed_list.get(position).getMerchId();
				for(int i = 0;i<merch_list.size();i++){
					if(merch_list.get(i).getMerchId().equals(merchId)){
						Merchant merchant = merch_list.get(i);
						ProductListActivity.merchant = merchant;
						Intent intent = new Intent(HomeActivity.this,ProductListActivity.class);
						startActivity(intent);
						break;
					}
				}
			}

		});
		
		View btnMap =(View) findViewById(R.id.btn_map);
		btnMap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(HomeActivity.this,MapActivity.class);
				startActivity(intent);

			}
		});
//		btnShare = findViewById(R.id.btn_magazine);
//		btnShare.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Utility.shareFacebook(HomeActivity.this, "http://stackoverflow.com/questions/7545254");
//				
//			}
//		});
		
		
		btnChannel = findViewById(R.id.btn_magazine);
		btnChannel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomeActivity.this,ChannelActivity.class);
				startActivity(intent);
				
			}
		});
		
		
		btnAccount = (View)findViewById(R.id.btn_account);
		btnAccount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				getUserinfo();
				
				
			}
		});
		
		try {
			File httpCacheDir = new File(this.getCacheDir(), "http");
			long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
			Class.forName("android.net.http.HttpResponseCache")
					.getMethod("install", File.class, long.class)
					.invoke(null, httpCacheDir, httpCacheSize);
		} catch (Exception httpResponseCacheNotAvailable) {
		}

		if (Utility.checkInternetConnection(HomeActivity.this) == true) {
			// Dialog
			waitDialog = new ProgressDialog(HomeActivity.this);
			waitDialog.setMessage("Please wait...");
			waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			waitDialog.show();
			/* get data from server */
			getMerchData();
			autoRegDevice();
		}
		
	}
	
	public void getUserinfo(){
		String userId = new BooPreference(this).getPref()
				.getString(BooPreference.KEY_USER_ID, "").toString();
		if(userId.equals("")){
			startActivity(new Intent(HomeActivity.this, UpdateInfoActivity.class));
		}
		else{
			try{
				final SendDataService service  = new SendDataService(this);
				JSONObject jsonparams = new JSONObject();
				jsonparams.put("custId", userId);
				service.sendData(Constant.API_GET_USERINFO, jsonparams, new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(JSONObject response) {		
						try {
							JSONObject result = response.getJSONObject("Result");
							String userStr = result.toString();
							Gson gson = new Gson();
							HomeActivity.userInfo = gson.fromJson(userStr, ObjUser.class);
							startActivity(new Intent(HomeActivity.this, UpdateInfoActivity.class));
							service.setCache(Constant.API_GET_USERINFO, response.toString());

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
											}

					@Override
					public void onFailure(Throwable error) {
						Log.d("failure", "is " + error.getMessage());
						error.printStackTrace();
					}
				});
			}
			catch (Exception e){
			}
				
			}
	}
	
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
//		HttpResponseCache cache = HttpResponseCache.getInstalled();
//		if (cache != null) {
//			cache.flush();
//		}
	}
	
	private void autoRegDevice(){
		AccountService accService = new AccountService(HomeActivity.this);
		
		// auto register
		accService.autoRegister();
	}
	
	private void getMerchData() {
		final SendDataService service  = new SendDataService(this);
		service.sendData(Constant.API_GET_MERCHANT_URL, new JSONObject(), new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(JSONArray response){
				Log.d("get merch array ", " is " + response);
			}
			@Override
			public void onSuccess(JSONObject response) {
				Log.d("get merch object", " is " + response);
				afterMerch(response);
				service.setCache(Constant.API_GET_MERCHANT_URL, response.toString());
			}

			@Override
			public void onFailure(Throwable error) {
				Log.d("failure", "is " + error.getMessage());
				error.printStackTrace();
			}
		});
	}
	private void getFeedData() {
		final SendDataService service  = new SendDataService(this);
		service.sendData(Constant.API_GET_FEED_URL, new JSONObject(), new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(JSONArray response){
				Log.d("get merch", " is " + response);
			}
			@Override
			public void onSuccess(JSONObject response) {
				Log.d("get feed", " is " + response);
				afterFeed(response);
				service.setCache(Constant.API_GET_FEED_URL, response.toString());
			}

			@Override
			public void onFailure(Throwable error) {
				Log.d("ThuanHM", "fead error is " + error.getMessage());
				error.printStackTrace();
			}
		});
		
//		Log.d("", "get feed");
//		FeedService feedService = new FeedService(HomeActivity.this);
//
//		// get user history by using email
//		feedService.getData(Constant.API_GET_FEED_URL);
	}

	private void updateData(){
		if(feed_list.size()>0){
			feedAdapter.notifyDataSetChanged();
		}	
		waitDialog.dismiss();
	}
	
	public void afterMerch(JSONObject response){
		
		ArrayList<Merchant> lstTmp = new ArrayList<Merchant>();
		try {
			JSONArray listMerch = response.getJSONArray("Merchants");
			if(listMerch!=null){
				Gson gson = new Gson();
				for (int i = 0; i < listMerch.length(); i ++){
					JSONObject memberJsonInfo = listMerch.getJSONObject(i);
					String stringInfo = memberJsonInfo.toString();
					Merchant newMerch = gson.fromJson(stringInfo, Merchant.class);
					lstTmp.add(newMerch);
				}
				if(merch_list.size() == lstTmp.size()){	// should deep compare is better!
					Log.e("Cache", "Not need reload");
					return;
				}
				merch_list.clear();
				for(Merchant merchant : lstTmp){
					merch_list.add(merchant);
				}
				getFeedData();
			}
		} catch (Exception e) {
		}

	}
	public void afterFeed(JSONObject response){
		
		ArrayList<Feed> feedTmp = new ArrayList<Feed>();
		try {
			JSONArray listFeed = response.getJSONArray("Feeds");
			if(listFeed!=null){
				Gson gson = new Gson();
				for (int i = 0; i < listFeed.length(); i ++){
					JSONObject memberJsonInfo = listFeed.getJSONObject(i);
					String stringInfo = memberJsonInfo.toString();
					Feed newFeed = gson.fromJson(stringInfo, Feed.class);
					feedTmp.add(newFeed);
				}
				if(feed_list.size() == feedTmp.size()){	// should deep compare is better!
					Log.e("Cache", "Not need reload");
					return;
				}
				feed_list.clear();
				for(Feed feed: feedTmp){
					feed_list.add(feed);
				}
				for(int i = 0; i < feed_list.size();i++){
					String merchId = feed_list.get(i).getMerchId();
					for(int j = 0; j < merch_list.size();j++){
						if (merchId.equalsIgnoreCase(merch_list.get(j).getMerchId())){
							feed_list.get(i).setStoreImageLink(merch_list.get(j).getMerchantImageLink());
							break;
						}
					}
				}
			}
			updateData();
		} catch (Exception e) {
		}
	}
}
